import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";
import {Buffer} from "buffer";
import {OAD} from "./OAD";
import {Get_Result} from "./Get_Result";


export class ProxyGet implements AxdrType{

    dataCode : Buffer | null = null;
    oad : OAD | null = null;
    result : Get_Result | null = null;

    constructor() {
    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_all(oad : OAD, result : Get_Result){
        this.oad = oad;
        this.result = result;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.oad = new OAD();
        codeLength += this.oad.decode(input);

        this.result = new Get_Result();
        codeLength += this.result.decode(input);

        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.result != null && this.oad != null){
                codeLength = 0;
                codeLength += this.result.encode(output);
                codeLength += this.oad.encode(output);
            }else{
                throw new Error("oad || result is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.oad != null && this.result != null) {
            return "sequence: {"+ "oad: " + this.oad + ", result: " + this.result  + "}";
        } else {
            return "oad || result is null";
        }
    }

}
